package com.bawei.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.es.service.EsIndexService;
import com.bawei.system.domain.CreateEsinfo;
import com.bawei.system.domain.EsMallProductInfo;
import com.bawei.system.domain.EsProduct;
import com.bawei.system.domain.SearchResult;
import com.bawei.system.domain.vo.PageVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class EsIndexServiceImpl implements EsIndexService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static  final  String INDEX_NAME="product_sku_info";

    @Override
    public R<Boolean> indexCreate(String indexName) {
        //如果索引为空 抛出异常
        if (StringUtils.isEmpty(indexName)) {
            throw new ServiceException("索引名称不能为空");
        }
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        try {
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            if (createIndexResponse.isAcknowledged()) {
                return R.ok(true);
            }
        } catch (IOException e) {
            log.error("连接ES服务异常:{}", e);
            throw new RuntimeException("创建索引失败，请联系管理员或查看服务日志");
        }
        return R.fail(false, "索引创建失败");
    }

    @Override
    public R<Boolean> indexExit(String indexName) {
        if (StringUtils.isEmpty(indexName)) {
            throw new ServiceException("indexName不能为空");
        }
        GetIndexRequest indexRequest = new GetIndexRequest(indexName);
        try {
            boolean exists = restHighLevelClient.indices().exists(indexRequest, RequestOptions.DEFAULT);
            return R.ok(exists);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.fail(false, "查询失败！");
    }

    @Override
    public R<Boolean> indexDelete(String indexName) {
        if (StringUtils.isEmpty(indexName)) {
            throw new ServiceException("indexName不能为空 ");
        }
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        try {
            AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
            if (delete.isAcknowledged()) {
                return R.ok(true, "删除成功！");
            }
        } catch (IOException e) {
            log.error("删除索引失败：{}", e);
            throw new RuntimeException("调用es服务删除索引失败，详情请查看日志");
        }
        return R.fail(false, "删除索引失败");
    }

    @Override
    public R<Boolean> indexCreateWithMapping(CreateEsinfo createEsinfo) {
        if (StringUtils.isEmpty(createEsinfo.getIndexName()) ||
                createEsinfo.getIndexMappings() == null ||
                createEsinfo.getIndexSettings() == null) {
            throw new ServiceException("indexName、indexMapping、indexSetting不能为空");
        }

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将indexMappings和indexSettings转换为JSON字符串
            String indexMappingsJson = objectMapper.writeValueAsString(createEsinfo.getIndexMappings());
            String indexSettingsJson = objectMapper.writeValueAsString(createEsinfo.getIndexSettings());

            CreateIndexRequest request = new CreateIndexRequest(createEsinfo.getIndexName());
            request.source(indexMappingsJson, XContentType.JSON);

            // 设置索引的settings
            if (StringUtils.isNotEmpty(indexSettingsJson)) {
                request.settings(indexSettingsJson, XContentType.JSON);
            }

            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            if (createIndexResponse.isAcknowledged()) {
                return R.ok(true, "创建索引成功");
            }
        } catch (IOException e) {
            log.error("调用ES创建索引异常：{}", e);
            throw new RuntimeException("创建索引失败", e);
        }
        return R.fail(false, "创建索引失败");
    }


    @Override
    public R<Map<String, Object>> indexGtMapping(String indexName) {
        R<Map<String, Object>> result = new R<>();
        Map<String, Object> dataMap = new HashMap<>();

        // 获取映射信息
        GetMappingsResponse response = null;
        try {
            response = restHighLevelClient.indices().getMapping(new GetMappingsRequest().indices(indexName), RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        MappingMetaData mappingMetaData = response.mappings().get(indexName);
        Map<String, Object> mappingSourceMap = mappingMetaData.sourceAsMap();

        // 获取设置
        GetSettingsRequest settingsRequest = new GetSettingsRequest().indices(indexName);
        GetSettingsResponse settingsResponse = null;
        try {
            settingsResponse = restHighLevelClient.indices().getSettings(settingsRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ImmutableOpenMap<String, Settings> indexToSettings = settingsResponse.getIndexToSettings();
        Settings indexSettings = indexToSettings.get(indexName);

        // 将Settings转换为Map<String, String>
        Map<String, String> settingsMap = new HashMap<>();
        for (String key : indexSettings.keySet()) {
            settingsMap.put(key, indexSettings.get(key));
        }

        // 将映射信息和设置加入到结果中
        dataMap.put("settings", settingsMap);
        dataMap.put("mappings", mappingSourceMap);

        result.setData(dataMap);
        return result;
    }

    @Override
    public R<Boolean> indexUpdate(String indexName, EsMallProductInfo esMallProductInfo) {
        UpdateRequest request = new UpdateRequest();
        try {
            request.index(indexName).id(esMallProductInfo.getId()+"");
            // 拓展：局部更新也可以这样写：request.doc(XContentType.JSON, "name", "李四", "age", 25);，其中"name"和"age"是User对象中的字段名称，而"小美"和20是对应的字段值
            request.doc(JSONObject.toJSONString(esMallProductInfo), XContentType.JSON);
            // 3、发送请求到ES
            UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public List<String> getAllIndex() {
        List<String> list = new ArrayList<>();
        GetIndexRequest request = new GetIndexRequest("_all"); // "_all" 表示所有索引
        GetIndexResponse getIndexResponse = null;
        try {
            getIndexResponse = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 从响应中提取索引名列表
        for (String index : getIndexResponse.getIndices()) {
            list.add(index);
        }
        return list;
    }
}
